<template>
	<div>
		<!-- <div class="title">Echarts中国地图三级钻取</div> -->
		<div class="box">
			<!-- <button class="backBtn" @click="back()">返回上级</button> -->
			<div ref="mapChart" class="chart"></div>
		</div>

	</div>
</template>

<script>
	import cityMap from "../charts/china-main-city-map";
	import echarts from "echarts";
	import axios from "axios";
	import Vue from "vue";
	import api from '@/api/api'
	// import registerAndsetOption from '@/js/echarts-map'


	export default {
		name: "MainMap",
		props: {
			msg: String
		},
		data() {
			return {
				//中国地图（第一级地图）的ID、Name、Json数据
				chinaId: 100000,
				chinaName: "china",
				chinaJson: null,
				//记录父级ID、Name
				mapStack: [],
				parentId: null,
				parentName: null,

				//Echarts地图全局变量，主要是在返回上级地图的方法中会用到
				myChart: this.$refs.mapChart,
				mapData: this.$store.state.mapData
			}
		},
		mounted() {
      this.initMapData()
			this.mapChart();
		},
		watch:{
			mapData:{
				handler(newVal, oldVal){
          axios.get("./static/json/map/" + this.chinaId + ".json", {}).then(response => {
            const mapJson = response.data;
            this.registerAndsetOption(this.myChart, this.chinaId, this.chinaName, mapJson, false);
          })
        },
        deep: true
			}
		},
		methods: {
			registerAndsetOption(myChart, id, name, mapJson, flag) {
				echarts.registerMap(name, mapJson);
				let data = this.$store.state.mapData
				myChart.setOption({
					tooltip: {
						show: true,
						trigger: 'item',
						axisPointer: {
							lineStyle: {
								color: '#57617B' //显示竖线颜色
							}
						},
						backgroundColor: '#05042C', //tooltip背景色
						borderColor: '#2BEDF6', //tooltip边框颜色
						borderWidth: 2,
						formatter: function(param) { //自定义tooltip内容
							// console.log(param)
							var text = '';
							text += '<div style="display:flex;flex-direction:row;">' +
								'<div style="background-color:#03D16D;height:auto;width:10px;margin-right:5px;"></div>' +
								'<div style="display:flex;flex-direction:column;">' +
								'<span>' + param.name + '</span>' +
								'<span>' + param.value + '</span>'
							'</div>'
							'</div>'
							return text;
						}
					},
					series: [{
						type: "map",
						map: name,
						itemStyle: {
							normal: {
								areaColor: "rgba(23, 27, 57,0)",
								borderColor: "#1dc199",
								borderWidth: 1
							}
						},
						label: {
							normal: {
								textStyle: {
									fontSize: 1
								}
							}
						},
						data: data
					}]
				});

				if (flag) {
					//往mapStack里添加parentId，parentName,返回上一级使用
					this.mapStack.push({
						mapId: this.parentId,
						mapName: this.parentName
					});
					this.parentId = id;
					this.parentName = name;
				}
			},

			async initMapData(mapJson) {
				// var mapData = [];
				// for (var i = 0; i < mapJson.features.length; i++) {
				// 	mapData.push({
				// 		name: mapJson.features[i].properties.name,
				// 		value: 12312
				// 		//id:mapJson.features[i].id
				// 	});
				// }
				// return mapData;
        axios.get("./static/json/map/" + this.chinaId + ".json", {}).then(response => {
          const mapJson = response.data;
          api.getMapData().then(res => {
            mapJson.features.filter(item=>{
              let name = item.properties.name;
              let value = 0;
              for (let i = 0; i<res.data.length;i++){
                if (res.data[i]['name'] === name){
                  value = res.data[i]['value']
                }
              }
              this.$store.commit(
                "setMapData",
                {
                  name: name,
                  value: value
                })
            })
          })
        })
			},
			mapChart() {
				axios.get("./static/json/map/" + this.chinaId + ".json", {}).then(response => {
					let that = this;
					const mapJson = response.data;
					that.chinaJson = mapJson;
					that.myChart = echarts.init(that.$refs.mapChart);
					that.registerAndsetOption(that.myChart, that.chinaId, that.chinaName, mapJson, false);
					that.parentId = that.chinaId;
					that.parentName = "china";
					that.myChart.on("click", function(param) {
            // 表的新名字
            that.$store.commit("setTitle",param.name)

						var cityId = cityMap[param.name];
						if (cityId) {
              api.getSchoolsByProvince(param.name).then(res=>{
                console.log(res)
                let table_data = res.data.map(item => {
                  let info_data = []
                  info_data.push(item['schoolName'])
                  // info_data.push(item['province'])
                  info_data.push(
                    `<a href="${item['schoolUrl']}" target="_blank">${item['schoolUrl']}</a>`
                  )
                  return info_data
                })
                that.$store.commit("setConfigHeader",['学校名称','学校链接'])
                if (table_data.length === 0) return 0;
                // console.log(table_data);
                that.$store.commit("setConfigData",table_data)

              })

							//代表有下级地图
							axios
								.get("./static/json/map/" + cityId + ".json", {})
								.then(response => {
									const mapJson = response.data;
									that.registerAndsetOption(
										that.myChart,
										cityId,
										param.name,
										mapJson,
										true
									);
								});
						} else {
							//没有下级地图，回到一级中国地图，并将mapStack清空
              that.$store.commit("setTitle","高校人数排行榜")
              // let store_config = this.$store.state.config
              // that.$store.commit("setConfig",store_config)
							that.registerAndsetOption(that.myChart, that.chinaId, that.chinaName, that
								.chinaJson, false);
              api.getSchoolFeverList().then(res=>{
                let table_data = res.data.map(item => {
                  let info_data = []
                  info_data.push(item['schoolName'])
                  info_data.push(item['city'])
                  info_data.push(item['num'])
                  return info_data
                })
                that.$store.commit("setConfigHeader",['学校', '城市', '报考人数'])
                that.$store.commit("setConfigData",table_data)
              })
							that.mapStack = [];
							that.parentId = that.chinaId;
							that.parentName = that.chinaName;
						}
					});
				});
			}
		}
	};
	/**
	 *
	 * @param {*} myChart
	 * @param {*} id        省市县Id
	 * @param {*} name      省市县名称
	 * @param {*} mapJson   地图Json数据
	 * @param {*} flag      是否往mapStack里添加parentId，parentName
	 */
</script>



<style scoped>
	.title {
		width: 100%;
		height: 10vh;
		text-align: center;
		color: #fff;
		font-size: 2em;
		line-height: 10vh;
	}

	.box {
		position: relative;
		width: 119%;
		height: 85vh;
		left: 8%;
		top: 10%;
		/* background-color: #FFF; */
	}

	.chart {
		position: relative;
		height: 100%;
		top: -2%;
		left: -12%;
	}

	.backBtn {
		position: absolute;
		top: 0;
		background-color: #00c298;
		border: 0;
		color: #fff;
		height: 27px;
		font-family: Microsoft Yahei;
		font-size: 1em;
		cursor: pointer;
	}

	.myBlog {
		position: absolute;
		top: 2px;
		right: 5%;
		display: block;
		border: 2px solid #262a53;
	}

	.myBlog a {
		text-decoration: none;
		display: inline-block;
		color: #fff;
		padding: 5px;
		font-size: 1em;
	}

	.myBlog a img {
		vertical-align: middle;
		height: 20px;
		width: 20px;
		border-radius: 50%;
		margin: -5px 5px auto auto;
	}

	.bottom {
		position: absolute;
		width: 100%;
		height: 5%;
		line-height: 100%;
		left: 0;
		bottom: 0%;
		text-align: center;
	}
</style>
